/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.user.myapplication;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import com.example.user.myapplication.utils.CustomExpandableListView;
import java.util.UUID;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * For a given BLE device, this Activity provides the user interface to connect, display data,
 * and display GATT services and characteristics supported by the device.  The Activity
 * communicates with {@code BluetoothLeService}, which in turn interacts with the
 * Bluetooth LE API.
 * 对于一个给定的BLE设备，本次活动提供连接的用户界面，显示数据，
 * 关贸总协定和显示设备所支持的服务特性。活动
 * 在“代码blue tooth le service } {通信，进而与
 * 蓝牙技术。
 */
public class DeviceControlActivity extends Activity {
    private Button btn_photo;
    //设置返回码：标识本地图库
    private static final int RESULT_IMAGE=100;
    //设置MIME码：表示image所有格式的文件均可
    private static final String IMAGE_TYPE="image/*";

    private final static String TAG = DeviceControlActivity.class.getSimpleName();

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
    private static DeviceControlActivity mThis = null;
    private boolean mServicesRdy = false;

    private TextView mConnectionState;
    private TextView mDataField;
    private String mDeviceName;
    private String mDeviceAddress;
    private CustomExpandableListView mGattServicesList;
    private BluetoothLeService mBluetoothLeService;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<>();
    private boolean mConnected = false;
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    public static final UUID OAD_SERVICE_UUID = UUID.fromString("f000ffc0-0451-4000-b000-000000000000");
    public static final UUID CC_SERVICE_UUID = UUID.fromString("0000ccc0-0000-1000-8000-00805f9b34fb");

    private BluetoothGattService mOadService = null;
    private BluetoothGattService mConnControlService = null;
    private List<BluetoothGattService> mServiceList = null;

    private final String LIST_NAME = "NAME";
    private final String LIST_UUID = "UUID";

    public static DeviceControlActivity getInstance() {
			return mThis;
		}

    // Code to manage Service lifecycle.
    // 管理服务生命周期的代码。
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            // 在成功的启动初始化时自动连接到设备
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    // Handles various events fired by the Service. 处理服务的各种事件。
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    // or notification operations.
    /**
     *  通过代码的形式动态的注册广播的接收者，
     *  广播接收者。用来接收发送过来的广播的。
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);
                //以前的菜单无效了，会创建新的菜单
                invalidateOptionsMenu();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                //显示连接的状态
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                //当处在不链接的状态的时候，会吧ListView的显示去掉
                clearUI();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                //显示用户界面上的所有支持的服务和特性。
								displayServices();
								checkOad();
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                                //通过Intent获取到传过来的值。
								byte [] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
  							String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
  							if (uuidStr.equals(mBluetoothLeService.mCharIdentify.getUuid().toString())
									&& (value != null)) {
  								// Image info notification
                                    mBluetoothLeService.mTargImgHdr.ver = buildUint16(value[1], value[0]);
                                    mBluetoothLeService.mTargImgHdr.imgType = ((mBluetoothLeService.mTargImgHdr.ver & 1) == 1) ? 'B' : 'A';
                                    mBluetoothLeService.mTargImgHdr.len = buildUint16(value[3], value[2]);
                                /**
                                 *Data初始值的设定
                                 */
									String s = String.format("Ver:%d Img:%c Type:%c%c%c%c", (mBluetoothLeService.mTargImgHdr.ver >> 1),
										mBluetoothLeService.mTargImgHdr.imgType, value[4], value[5], value[6], value[7]);

									displayData(s);
  								    mBluetoothLeService.displayImageInfo(mBluetoothLeService.mTargImgHdr);
									mBluetoothLeService.updateBTFirmware();
  							}								
								else if (value != null && value.length > 0) {
										final StringBuilder stringBuilder = new StringBuilder(value.length);
										for(byte byteChar : value)
                                            stringBuilder.append(String.format("%02X ", byteChar));
										intent.putExtra(BluetoothLeService.EXTRA_DATA, new String(value) + "\n" + stringBuilder.toString());
                                /**
                                 * 设置Data的值，首先获取到的值是根据intent传递的值的不同uuid而传过来的值是不同的。
                                 */
										displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
								}

                                } else if (BluetoothLeService.ACTION_WARNNING.equals(action)) {
							            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };

    /**
     * 当Intent在组件间传递时，组件如果想告知Android系统自己能够响应和处理哪些Intent
     * 那么就需要用到IntentFilter对象。动态的添加action
     */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_WARNNING);
        return intentFilter;
    }
    // If a given GATT characteristic is selected, check for supported features.  This sample
    // demonstrates 'Read' and 'Notify' features.  See
    // http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete
    // list of supported characteristic features.
    /**
     * 可扩展的ListView点击的事件。
     */
    private final ExpandableListView.OnChildClickListener servicesListClickListner =
            new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                            int childPosition, long id) {
                    if (mGattCharacteristics != null) {
                        final BluetoothGattCharacteristic characteristic =
                                mGattCharacteristics.get(groupPosition).get(childPosition);
                        //获取BluetoothGattDescriptor
                        final int charaProp = characteristic.getProperties();
                        // | 是位或运算，比如00001111和00110011进行位或就是00111111。除了0|0 = 0
                        //   其它0|1  1|0  1|1 结果都是1
                        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                            // If there is an active notification on a characteristic,clear
                            // 如果有一个主动通知的一个特征，清楚的
                            // it first so it doesn't update the data field on the user interface.
                            // 它首先所以它不更新用户界面上的数据字段。
                            if (mNotifyCharacteristic != null) {
                                mBluetoothLeService.setCharacteristicNotification(
                                        mNotifyCharacteristic, false);
                                mNotifyCharacteristic = null;
                            }
                            mBluetoothLeService.readCharacteristic(characteristic);
                        }
                        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                            mNotifyCharacteristic = characteristic;
                            mBluetoothLeService.setCharacteristicNotification(
                                    characteristic, true);
                        }
                        if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                                mBluetoothLeService.writeCharacteristic(characteristic);
                        }
                        return true;
                    }
                    return false;
                }
    };
    /**
     * 如果出来现链接断开的情况就清除UI。state设置为nodata。
     */
    private void clearUI() {
        mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
        mDataField.setText(R.string.no_data);
    }

    /**
     * 创建布局
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gatt_services_characteristics);

				mThis = this;
        /**
         * 接受点击设备跳转过来的值。设备name和设备的address
         */
        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
        mServiceList = new ArrayList<>();

        /**
         * 设置点击按钮进入图库
         */
        btn_photo = (Button) findViewById(R.id.btn_photo);
        btn_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //实例化Intent,传入ACTION_PICK,表示从Item中选取一个数据返回
                Intent intent=new Intent(Intent.ACTION_PICK,null);
                //设置Data和Type属性，前者是URI：表示系统图库的URI,后者是MIME码
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,IMAGE_TYPE);
                //启动这个intent所指向的Activity
                startActivityForResult(intent,RESULT_IMAGE);
            }
        });
        //TODO 点击进入手机图库。可以先择图片来进行传递
        // Sets up UI references.
        //找到控件的Id。
        ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
        mGattServicesList = (CustomExpandableListView) findViewById(R.id.gatt_services_list);
        mGattServicesList.setOnChildClickListener(servicesListClickListner);
        mConnectionState = (TextView) findViewById(R.id.connection_state);
        mDataField = (TextView) findViewById(R.id.data_value);

        getActionBar().setTitle(mDeviceName);
        //给左上角图标的左边加上一个返回的图标
        getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }
    //在onResume中注册广播，可以避免系统资源的浪费
    @Override
    protected void onResume() {
        super.onResume();
        //注册广播，（广播接收者，intent的action 事件）
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        //判断服务是否链接
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }
    //在onPause中注销广播。
    @Override
    protected void onPause() {
        super.onPause();
        //注销
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }
    //创建菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gatt_services, menu);
        if (mConnected) {
            menu.findItem(R.id.menu_connect).setVisible(false);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(false);
        }
        return true;
    }
    //菜单选项。菜单点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_connect:
                mBluetoothLeService.connect(mDeviceAddress);
                return true;
            case R.id.menu_disconnect:
                mBluetoothLeService.disconnect();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    //断开链接
    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mConnectionState.setText(resourceId);
            }
        });
    }
    //设置data的内容
    public void displayData(String data) {
        if (data != null) {
            mDataField.setText(data);
        }
    }

    // Demonstrates（演示） how to iterate through the supported GATT Services/Characteristics.
    // In this sample, we populate the data structure that is bound to the ExpandableListView
    //在本示例中，我们将被绑定到可扩展的列表视图的数据结构
    // on the UI.
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().getString(R.string.unknown_service);
        String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<>();
        mGattCharacteristics = new ArrayList<>();

        // Loops through available GATT Services.
        //循环通过关贸总协定的服务提供。
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData = new HashMap<>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<>();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(
                        LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
        }
        /**
         * 为expandListView设置数据。首先是外层的listView的数据的设定。数据为HashMap，key为List-Name
         * value为SampleGattAttributes.lookup(uuid, unknownCharaString)方法所对应的名字。为第一个gettServiceData的
         * 集合所代表的数据。。
         * 第二层的数据为gattCharacteristicData数据集合所对应的数据。
         */
        SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
                this,
                //数据聚合
                gattServiceData,
                //外层ListView所对应的布局
                android.R.layout.simple_expandable_list_item_2,
                //对应的数据
                new String[] {LIST_NAME, LIST_UUID},
                //对应的控件的id
                new int[] { android.R.id.text1, android.R.id.text2 },
                gattCharacteristicData,
                android.R.layout.simple_expandable_list_item_2,
                new String[] {LIST_NAME, LIST_UUID},
                new int[] { android.R.id.text1, android.R.id.text2 }
        );
        mGattServicesList.setAdapter(gattServiceAdapter);
    }

    /**
     * 进制之间的转换，是的包括二进制和十进制和十六进制之间的转换。
     * bytes[0] = (byte) (data & 0xff):变量data与 0xff进行按位与运算(这里就是将高8位置0)，
     * 然后强制转换成byte类型，赋值给byte数组的元素byte[0]
     */
		private static byte loUint16(short v) {
			return (byte) (v & 0xFF);
		}
		
		private static byte hiUint16(short v) {
			return (byte) (v >> 8);
		}
		
		private static short buildUint16(byte hi, byte lo) {
			return (short) ((hi << 8) + (lo & 0xff));
		}

		private void checkOad() {
			// Check if OAD is supported (needs OAD and Connection Control service)
            //检查情况（需要支持外接控制服务）
			mOadService = null;
			mConnControlService = null;
		
			for (int i = 0; i < mServiceList.size() && (mOadService == null || mConnControlService == null); i++) {
				BluetoothGattService srv = mServiceList.get(i);
				if (srv.getUuid().equals(OAD_SERVICE_UUID)) {
					mOadService = srv;
				}
				if (srv.getUuid().equals(CC_SERVICE_UUID)) {
					mConnControlService = srv;
				}
			}
			mBluetoothLeService.getOADService();
		}

		private void displayServices() {
			mServicesRdy = true;
		
			try {
				mServiceList = mBluetoothLeService.getSupportedGattServices();
			} catch (Exception e) {
				e.printStackTrace();
				mServicesRdy = false;
			}
		
			// Characteristics descriptor readout done
            //完成的特征描述符读出
			if (mServicesRdy) {
//				setStatus("Service discovery complete");
//				enableSensors(true);
//				enableNotifications(true);
			} else {
//				setError("Failed to read services");
			}
		}

		BluetoothGattService getOadService() {
			return mOadService;
		}

		BluetoothGattService getConnControlService() {
			return mConnControlService;
		}
}
